﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using VOL.Core.DBManager;
using VOL.Core.ManageUser;
using VOL.Entity.DomainModels;
using syio = System.IO;

namespace VOL.Core.Utilities
{
    public class weixin_tools
    {
       
       //使用样例 
                   /* openidstr = "oGHE6wnHTISjdy2vTW4XO41OvEU4";//提醒给hxs
                    string str1 = weixin_tools.dcl_temp_str;//使用的时候需要只提供消息字符串模版
                    str1 = str1.Replace("@openid@", openidstr);
                    str1 = str1.Replace("@url@", "http://ksh1.ctruck.com.cn");
                    str1 = str1.Replace("@keyword1@", "业务编号:XX");
                    str1 = str1.Replace("@keyword2@", "报销审批提醒");
                    str1 = str1.Replace("@keyword3@", user.UserTrueName);
                    str1 = str1.Replace("@keyword4@","待处理状态");
                    str1 = str1.Replace("@keyword5@", DateTime.Now.ToString());
                    str1 = str1.Replace("@remark@", "");
                    weixin_tools.SendTempletMessge(str1);*/
        
        private static string appid_str = "wx7897cb67b0a0b45e";
        private static string secret_str = "d24377ec3e6c178cf8d1b9523998591b";
        /// <summary>
        /// 预警模版
        /// </summary>
        private static string yj_tempid = "OalDL1h6gMJsTgi3XLsmHSS1IYuEdalipUEgGHWvpCU";//预警模版id
        public static string yj_temp_str = "{\"touser\": \"@openid@\"," + //预警模版字符串
                       "\"template_id\": \"" + yj_tempid + "\", " +
                       "\"url\": \"@url@\", " +
                       "\"topcolor\": \"#FF0000\", " +
                       "\"data\": " +
                       "{\"first\": {\"value\": \"\"}," +
                       "\"keyword1\": { \"value\": \"@keyword1@\"}," +//预警内容
                       "\"keyword2\": { \"value\": \"@keyword2@\"}," + //预警时间
                       "\"remark\": {\"value\": \"@remark@\" }}}";

        /// <summary>
        /// 待处理提醒
        /// </summary>
        private static string dcl_tempid = "ewJUGX0Eu0W0esSShZyCleLB1gdTNiXmikXnDODErcE";//待处理提醒模版id
        
        public static string dcl_temp_str = "{\"touser\": \"@openid@\"," +
                       "\"template_id\": \"" + dcl_tempid +"\", " +
                       "\"url\": \"@url@\", " +
                       "\"topcolor\": \"#FF0000\", " +
                       "\"data\": " +
                       "{\"first\": {\"value\": \"\"}," +
                       "\"keyword1\": { \"value\": \"@keyword1@\"}," +//工单编号
                       "\"keyword2\": { \"value\": \"@keyword2@\"}," + //工单标题
                       "\"keyword3\": { \"value\": \"@keyword3@\"}," +//发起人
                       "\"keyword4\": { \"value\": \"@keyword4@\"}," + //工单状态，待处理
                       "\"keyword5\": { \"value\": \"@keyword5@\"}," + //开始时间
                       "\"remark\": {\"value\": \"@remark@\" }}}";
        /// <summary>
        /// 待处理信息发送
        /// </summary>
        /// <param name="tousername">登录名称</param>
        /// <param name="message_str"></param>
        public static void SendTempletMessge_dcl(string tousername,string message_str)
        {
            try
            {
                string fromuser = UserContext.Current.GetUserInfo(UserContext.Current.UserId).UserTrueName;
                Wxgzh_login_map wx_map = DBServerProvider.DbContext.Set<Wxgzh_login_map>().Where(s => s.uname == tousername).FirstOrDefault();
                if (wx_map == null) return;
                string touser_openid = wx_map.openid;
                //openidstr = "oGHE6wnHTISjdy2vTW4XO41OvEU4";//提醒给hxs
                string str1 = weixin_tools.dcl_temp_str;//使用的时候需要只提供消息字符串模版
                str1 = str1.Replace("@openid@", touser_openid);
                str1 = str1.Replace("@url@", "http://ksh1.ctruck.com.cn");
                str1 = str1.Replace("@keyword1@", message_str);
                str1 = str1.Replace("@keyword2@", "报销审批提醒");
                str1 = str1.Replace("@keyword3@", fromuser);
                str1 = str1.Replace("@keyword4@", "待处理状态，请及时处理！");
                str1 = str1.Replace("@keyword5@", DateTime.Now.ToString());
                str1 = str1.Replace("@remark@", "");
                weixin_tools.SendTempletMessge(str1);
            }
            catch
            {
                return;
            }

        }
        public static string SendTempletMessge(string tempstr)
        {
            //公众号发生信息之前需要在公众号管理后台把消息模版加入到管理里面来，才可以使用
            string strReturn = string.Empty;
            try
            {
                #region 获取access_token
                //string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx7897cb67b0a0b45e&secret=d24377ec3e6c178cf8d1b9523998591b";
                string apiurl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid_str + "&secret=" + secret_str;
                WebRequest request = WebRequest.Create(@apiurl);
                request.Method = "POST";
                WebResponse response = request.GetResponse();
                syio.Stream stream = response.GetResponseStream();
                Encoding encode = Encoding.UTF8;
                syio.StreamReader reader = new syio.StreamReader(stream, encode);
                string detail = reader.ReadToEnd();
                //var jd = JsonConvert.DeserializeObject<WXApi>(detail);
                dynamic jd = JsonConvert.DeserializeObject(detail);
                //string token = (String)jd.access_token;
                string token = jd.access_token;
                #endregion
                #region 组装信息推送，并返回结果（其它模版消息于此类似）
                string url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token;

                /*  string temp = "{\"touser\": \"" + openid + "\"," +
                         "\"template_id\": \"" + tempid + "\", " +
                         "\"topcolor\": \"#FF0000\", " +
                         "\"data\": " +
                         "{\"first\": {\"value\": \"@frist@\"}," +
                         "\"keyword1\": { \"value\": \"@keyword1@\"}," +
                         "\"keyword2\": { \"value\": \"@keyword2@\"}," +
                         "\"keyword3\": { \"value\": \"金额\"}," +
                         "\"keyword4\": { \"value\": \"业务员\"}," +
                         "\"remark\": {\"value\": \"\" }}}";
                  temp = temp.Replace("@frist@", "名称").Replace("@keyword2@", DateTime.Now.ToString());*/
                #endregion
                //核心代码
                GetResponseData(tempstr, @url);
                strReturn = "推送成功";
            }
            catch (Exception ex)
            {
                strReturn = ex.Message;
            }
            return strReturn;
        }
        /// <summary>
        /// 返回JSon数据
        /// </summary>
        /// <param name="JSONData">要处理的JSON数据</param>
        /// <param name="Url">要提交的URL</param>
        /// <returns>返回的JSON处理字符串</returns>
        private static string GetResponseData(string JSONData, string Url)
        {
            byte[] bytes = Encoding.UTF8.GetBytes(JSONData);
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
            request.Method = "POST";
            request.ContentLength = bytes.Length;
            request.ContentType = "json";
            syio.Stream reqstream = request.GetRequestStream();
            reqstream.Write(bytes, 0, bytes.Length);
            //声明一个HttpWebRequest请求
            request.Timeout = 90000;
            //设置连接超时时间
            request.Headers.Set("Pragma", "no-cache");
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            syio.Stream streamReceive = response.GetResponseStream();
            Encoding encoding = Encoding.UTF8;
            syio.StreamReader streamReader = new syio.StreamReader(streamReceive, encoding);
            string strResult = streamReader.ReadToEnd();
            streamReceive.Dispose();
            streamReader.Dispose();
            return strResult;
        }

    }
}
